package com.shiguiwu.springmybatis.spring.lifecycle.setprop;

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

/**
 * @description: 设置赋值前，如果返回false将不会被赋值
 *
 * 会调用 InstantiationAwareBeanPostProcessor 接口的 postProcessAfterInstantiation 这个方
 * 法，调用逻辑如下：，
 * 后续的Bean属性赋值前处理、Bean
 * 属性赋值都会被跳过了。
 * @author: stone
 * @date: Created by 2021/3/25 20:25
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.lifecycle.setprop
 */
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * 后续的Bean属性赋值前处理、Bean
     *  属性赋值都会被跳过了。
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
//        System.out.println("调用 MyInstantiationAwareBeanPostProcessor#postProcessAfterInstantiation");
        if ("pig1".equalsIgnoreCase(beanName)) {
            return false;
        }

        return true;
    }

    /**
     * 赋值操作
     * @param pvs
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        System.out.println("调用InstantiationAwareBeanPostProcessor #postProcessProperties");
        if ("pig".equals(beanName)) {
            if (pvs==null) {
                pvs = new MutablePropertyValues();
            }
            if (pvs instanceof MutablePropertyValues) {
                MutablePropertyValues pv = (MutablePropertyValues) pvs;
                //偷梁换柱，给属性辅助
                pv.add("name", "猪无能");
                pv.add("age", 12);
            }
        }
        return null;
    }
}
